package com.ambimmort.shj.service.generalfile;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Hfub;
import net.sf.json.JSONArray;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 师梁 on 2015/7/30.
 */
@Service("add_BlackUrlService")
public class Add_BlackUrlService {
    @Autowired
    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    public boolean add(String content){

        JSONArray arr = JSONArray.fromObject(content);
        boolean result = false;

        init();
        String hql = "from Hfub";
        try{
        for (int i = 0; i < arr.size(); i++) {
            String url = arr.get(i).toString();
            String sql = "select * from hfub where filter = '" + url + "'";
            Object[] params = {};
            rs = baseDao.executeSQL(sql, params);
            if (!rs.next()) {
                Object[] param = {url};
                sql = "insert into appdef (filter) values (?)";
                baseDao.executeUpdate(sql, param);
            }
        }
//            JSONArray arr = JSONArray.fromObject(content);
//            boolean result = false;
//        Session session = hibernateSessionFactory.openSession();
//        session.clear();
//        Transaction tx = session.beginTransaction();
//        String hql = "from Hfub";
//        List hfubs = session.createQuery(hql).list();
//        Map<String, Integer> map = new HashMap<String, Integer>();
//        if (!hfubs.isEmpty()) {
//            for (int i = 0; i < hfubs.size(); i++) {
//                Hfub hd = (Hfub) hfubs.get(i);
//                map.put(hd.getFilter(), hd.getId());
//            }
//        }
//        Hfub hfub = null;
//        try {
//            for (int i = 0; i < arr.size(); i++) {
//                String url = arr.get(i).toString();
//                if (!map.containsKey(url)) {
//                    hfub = new Hfub(url);
//                    session.save(hfub);
//                    int id = map.size() + 1;
//                    map.put(url, id);
//                }
//            }
////            tx.commit();
            result = true;
        } catch (Exception e) {
//            tx.rollback();
            result = false;
        } finally {
            close();
//            session.close();
//            sf.close();
        }

        return result;

    }

}
